<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="名称" prop="roleName">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate()"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-tabs v-model="activeType" @tab-click="typeHandleClick">
      <el-tab-pane
         v-for="item in typeArr"
         :name="item.value"
         :key="item.value"
         :label="item.label"
         :value="item.value"
      >
      </el-tab-pane>
    </el-tabs>

    <el-table
      v-loading="loading"
      :data="dataList"
      row-key="id"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" prop="name"  />
      <el-table-column label="编码" prop="typecode" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="显示顺序" prop="ordernum" width="100" />
      <el-table-column
        label="是否启用"
        prop="status">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="toggleStatus(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope" >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:role:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:role:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form :model="typeForm">
<!--        <el-form-item label="编码" :label-width="formLabelWidth">-->
<!--          <el-input v-model="typeForm.typecode" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="业务分类" :label-width="formLabelWidth">
          <el-select v-model="typeForm.bustype" placeholder="请选择">
            <el-option
              v-for="item in typeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" :label-width="formLabelWidth">
          <el-input v-model="typeForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="父级节点" :label-width="formLabelWidth">
          <el-cascader
            v-model="typeForm.parentid"
            :props="{ checkStrictly: true }"
            :options="typeList">
          </el-cascader>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth">
          <el-input v-model="typeForm.ordernum" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {deleteById, getList, getPageList, save, update} from "@/api/imgManage/imgType";
import {listToTree} from "@/utils";
export default {
  name: "imgType",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      activeType: 'imgType',
      typeArr: [
          { label: '图片分类', value: 'imgType' },
          { label: '合集分类', value: 'coll' },
          { label: '首页分类', value: 'home' },
          // { label: '爬取分类', value: 'crawler' }
      ],
      typeForm: {},
      formLabelWidth: '100px',
      typeList: [],
      dataList:[],
      allObj: { value:'all', label: '全部',id:'all', name: '全部' },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 200,
        name: undefined,
        bustype: 'imgType'
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      selectionRow: []
    };
  },
  async created() {
    await this.initTypeList()
    await this.getList();
  },
  mounted() {

  },
  methods: {
    async typeHandleClick() {
      this.queryParams.bustype = this.activeType; // 更新查询参数中的类型
      await this.initTypeList()
      this.getList();
    },
    async initTypeList(){
      let dataList = await getList().then(res => res.data )
      dataList = dataList?.filter(item => item.bustype === this.activeType)

      dataList.forEach((item) => {
        item.label = item.name
        item.value = item.id
      })
      const treeList = listToTree(dataList,'id','parentid')
      treeList.forEach((item) => {
        if(item?.children?.length === 0){
          delete item.children
        }
      })
      treeList.unshift(this.allObj)
      this.typeList = treeList
    },
    getList() {
      this.loading = true;
      this.dataList = []
      getPageList(this.queryParams, this.dateRange).then(response => {
          this.dataList = listToTree(response.rows,'id','parentid')
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectionRow = selection
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple =!selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.typeForm = Object.assign({ bustype: this.activeType })
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if(!row){
        row = this.selectionRow[this.selectionRow.length - 1]
      }
      this.reset();
      this.open = true;
      this.title = "修改";
      this.typeForm = Object.assign({}, row)
    },
    /** 提交按钮 */
    submitForm: function() {
      const submitObj = this.typeForm
      if(submitObj.parentid?.length === 0){
        submitObj.parentid = '0'
      }
      if(submitObj.parentid instanceof Array){
        submitObj.parentid = submitObj.parentid[submitObj.parentid.length - 1]
      }
      if(submitObj.id){
        update(submitObj).then(res => {
          this.open = false
          this.$modal.msgSuccess("修改成功");
          this.initTypeList()
          this.getList();
        })
      } else {
        save(submitObj).then(res => {
          this.open = false
          this.$modal.msgSuccess("新增成功");
          this.initTypeList()
          this.getList();
        })
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除数据？').then(function() {
        return deleteById({ ids: ids?.join(',') } );
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    toggleStatus(row) {
      const submitObj = Object.assign({}, row);
      update(submitObj).then(res => {
        this.$modal.msgSuccess("状态切换成功");
        this.getList();
      }).catch(() => {
        this.$modal.msgError("状态切换失败");
        // 回滚状态
        row.status = row.status === '0' ? '1' : '0';
      });
    },
  }
};
</script>
